<template>
  <a-tree-select :tree-data="mTreeData" :fieldNames="{
          key: valueField,
          label: labelField,
          children: childrenField,
          value: valueField
        }">
    <template v-for="item in slotKeys.filter(key=>props[key])" #[item]>
      <component :is="renderSlot(props,item)"/>
    </template>
  </a-tree-select>
</template>
<script setup lang="ts">
import { DefaultOptionType } from 'ant-design-vue/lib/vc-tree-select/TreeSelect';
import { PropType, VNode, onMounted, ref, watch } from 'vue';
import { renderSlot,requestData } from '..';
const slotKeys = ['searchPlaceholder','suffixIcon','tagRender','title','notFoundContent']

const props = defineProps({
  searchPlaceholder: {
    type: [String, Object, Function] as PropType<String | VNode |(()=>VNode | String)>
  },
  suffixIcon: {
    type: [String, Object, Function] as PropType<String | VNode |(()=>VNode | String)>
  },
  tagRender: {
    type: [String, Object, Function] as PropType<String | VNode |(()=>VNode | String)>
  },
  title: {
    type: [String, Object, Function] as PropType<String | VNode |(()=>VNode | String)>
  },
  notFoundContent: {
    type: [String, Object, Function] as PropType<String | VNode |(()=>VNode | String)>
  },
  treeData: {
    type: [Array] as PropType<DefaultOptionType[]>
  },
  api: { // 接口地址或接口函数--->新增属性
    type: [Function, String] as PropType<((param: any)=>Promise<any>) | String>
  },
  params: {
    type: Object,
    default(){
      return {}
    }
  },
  immediate: { // 是否立即加载数据
    type: Boolean,
    default: true
  },
  valueField: { // 值字段
    type: String,
    default: 'value'
  },
  labelField: { // 显示字段
    type: String,
    default: 'label'
  },
  childrenField: { // 子节点字段
    type: String,
    default: 'children'
  },
})
const mTreeData = ref(props.treeData || [])
watch(()=>props.treeData,()=>{
  mTreeData.value = props.treeData as any
},{
  deep: true
})
onMounted(()=>{
  if(props.immediate) {
    console.log('props.api',props.api);
    console.log('props.params',props.params);
    // console.log('props.params',props);
    requestData(props.api,props.params).then(res=>{
      // console.log('mTreeData----',res.content);
      
      const v = res.content || res
      if(v instanceof Array) {
        console.log('mTreeData----',props.treeData);
        mTreeData.value.push(v) 
        // mTreeData.value = v
      }
    })
    console.log('mTreeData.value',mTreeData.value);
    
  }
})
defineExpose({
  reload(params: any) {
    requestData(props.api,{
      ...props.params,
      ...params
    }).then(res=>{
      const v = res.data || res
      if(v instanceof Array) {
        mTreeData.value = v
      }
    })
  }
})
</script>
<style lang="less" scoped>

</style>